package com.bgs.engineering.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bgs.engineering.common.errorCode.EmErrorCode;
import com.bgs.engineering.common.response.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 用于远程上传图片工具类
 *
 * @auther zcy
 * @data 2023/3/17 14:10
 */
@Configuration
public class UploadFileUtils {

  private static String url;

  private static String delUrl;

  private static String projectName;

  private static String getImgUrl;

  @Value("${imageServer.url}")
  public void setToUrl(String url) {
    UploadFileUtils.url = url;
  }

  @Value("${imageServer.projectName}")
  public void setProjectName(String projectName) {
    UploadFileUtils.projectName = projectName;
  }

  @Value("${imageServer.delUrl}")
  public void setDelUrl(String delUrl) {
    UploadFileUtils.delUrl = delUrl;
  }

  @Value("${imageServer.getImgUrl}")
  public void setGetImgUrl(String getImgUrl) {
    UploadFileUtils.getImgUrl = getImgUrl;
  }


  /**
   * 批量上传
   *
   * @param files
   * @return
   */
  public static String uploadListFile(MultipartFile[] files) {
    // 用户拼接id
    StringBuilder ids = new StringBuilder();
    // 循环上传图片到服务器
    if (files != null && files.length > 0) {
      for (int i = 0; i < files.length; i++) {
        String id = uploadFile(files[i]);
        if (i == files.length - 1) {
          ids.append(id);
        } else {
          ids.append(id).append(",");
        }
      }
    } else {
      ids.append(0);
    }
    return ids.toString();
  }

  /**
   * 新增图片
   *
   * @param file
   * @return
   */
  public static String uploadFile(MultipartFile file) {
    String toUrl = url + "/" + projectName;
    // 判断对象是否为空
    if (file.isEmpty() && file.getSize() == 0) {
      return "";
    }
    // 获取字节
    byte[] fileByte = null;
    try {
      fileByte = file.getBytes();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    DataOutputStream dos = null;
    InputStream is = null;
    InputStreamReader isr = null;
    String end = "\r\n";
    String twoHyphens = "--";
    // 分隔符
    String boundary = "---------------------------823928434";
    try {
      //创建url连接
      URL url = new URL(toUrl);
      // 创建HttpURLConnection 连接
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      // 设置输入
      httpURLConnection.setDoInput(true);
      // 设置输出
      httpURLConnection.setDoOutput(true);
      // 不使用缓存
      httpURLConnection.setUseCaches(false);
      //连接超时 单位毫秒
      httpURLConnection.setConnectTimeout(10000);
      //读取超时 单位毫秒
      httpURLConnection.setReadTimeout(10000);
      // 设置请求方式
      httpURLConnection.setRequestMethod("POST");
      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
      // 设置字符集
      httpURLConnection.setRequestProperty("Charset", "UTF-8");
      // 设置Content-Type
      httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      dos = new DataOutputStream(httpURLConnection.getOutputStream());
      dos.writeBytes(twoHyphens + boundary + end);
      dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=" + file.getOriginalFilename() + end);
      dos.writeBytes(end);
      dos.write(fileByte);
      dos.writeBytes(end);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
      dos.flush();
      // 读取服务器返回结果
      is = httpURLConnection.getInputStream();
      isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String result = br.readLine();
      JSONObject jsonObject = JSON.parseObject(result);
      Boolean flag = jsonObject.getBoolean("flag");
      // 判断是否上传成共
      if (flag) {
        return getImgUrl + jsonObject.getString("data");
      } else {
        return "";
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      // 关闭读字符流
      if (isr != null) {
        try {
          isr.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      // 关闭字节输入流
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
      // 关闭数据输出流
      if (dos != null) {
        try {
          dos.close();
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return "";
  }


  /**
   * 删除图片及信息
   *
   * @param id
   * @return
   */
  public static boolean deleteFileById(Integer id) {
    if (id != 0 && isNotEmpty(delUrl)) {
      URL url = null;
      try {
        // 拼接id
        url = new URL(delUrl + "?id=" + id);
      } catch (MalformedURLException exception) {
        exception.printStackTrace();
      }
      InputStream is = null;
      InputStreamReader isr = null;
      HttpURLConnection httpURLConnection = null;
      try {
        httpURLConnection = (HttpURLConnection) url.openConnection();
        // 是遏制请求格式
        httpURLConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        // 设置请求方式
        httpURLConnection.setRequestMethod("DELETE");
        is = httpURLConnection.getInputStream();
        isr = new InputStreamReader(is, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String result = br.readLine();
        JSONObject jsonObject = JSON.parseObject(result);
        Boolean flag = jsonObject.getBoolean("flag");
        return flag;
      } catch (IOException exception) {
        exception.printStackTrace();
      } finally {
        if (httpURLConnection != null) {
          httpURLConnection.disconnect();
        }
        // 关闭读字符流
        if (isr != null) {
          try {
            isr.close();
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
        // 关闭字节输入流
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            throw new RuntimeException(e);
          }
        }
      }
    }
    return false;
  }

  /**
   * 判断字符串是个否为空
   *
   * @param str
   * @return
   */
  public static boolean isNotEmpty(String str) {
    return str != null && !"".equals(str);
  }

  /**
   * 判断是否为图片
   *
   * @param file 文件
   * @return
   */
  public static boolean isImage(MultipartFile file) {
    String[] types = {"jpeg", "jpg", "png", "gif", "bmp", "webp"};
    String contentType = file.getContentType();
    if (contentType == null) {
      return CommonResult.error(EmErrorCode.FILE_TYPE_ERROR).isFlag();
    }
    String type = contentType.substring(contentType.indexOf("/") + 1);
    boolean flag = false;
    for (String s : types) {
      if (s.equals(type)) {
        flag = true;
        break;
      }
    }
    return flag;
  }
}

